#!/usr/bin  python
# _*_ coding:utf-8 _*_
"""
----------------------------------
    File Name: adminuser
    Description:
        Author: lhw
        Date: 2020/7/1
-----------------------------------
"""
from rest_framework.views import APIView
from rest_framework.response import Response
from extensions.auth import JwtAuthorizationAuthentication
from Admin import models
from Admin.serializers import adminuser
from Common.logger import app_log
from Common.response import resp
from rest_framework.exceptions import ValidationError
from django.db.models import Q


class AdminUser(APIView):
    authentication_classes = [JwtAuthorizationAuthentication, ]

    def get(self, request, *args, **kwargs):
        try:
            params = request.query_params
            hospital = params["hospital"]
            role_type = params["role_type"]
            if hospital != "ALL":
                if role_type != "ALL":
                    user_query = models.AdminUser.objects.filter(hospital=hospital, role__title=role_type).all()
                else:
                    user_query = models.AdminUser.objects.filter(hospital=hospital).all()
            else:
                if role_type != "ALL":
                    user_query = models.AdminUser.objects.filter(role__title=role_type).all()
                else:
                    user_query = models.AdminUser.objects.all()
            user_data = adminuser.AdminUserModelSerializer(user_query, many=True).data
            return Response({
                'error_code': 0,
                'message': "Success",
                'data': user_data
            })
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)

    def post(self, request, *args, **kwargs):
        try:
            request_data = request.data
            user_ser = adminuser.AdminUserModelSerializer(data=request_data)
            user_ser.is_valid(raise_exception=True)
            user_obj = user_ser.save()
            return Response({
                'error_code': 0,
                'message': "Success",
                'data': adminuser.AdminUserModelSerializer(user_obj).data
            })
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)

    def put(self, request, *args, **kwargs):
        try:
            request_data = request.data
            user_id = request_data['id']
            old_user_obj = models.AdminUser.objects.filter(id=user_id).first()
            user_ser = adminuser.AdminUserModelSerializer(instance=old_user_obj, data=request_data)
            user_ser.is_valid(raise_exception=True)
            user_obj = user_ser.save()
            return Response({
                'error_code': 0,
                'message': "Success",
                'data': adminuser.AdminUserModelSerializer(user_obj).data
            })
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)

    def delete(self, request, *args, **kwargs):
        try:
            user_id = request.GET.get("id")
            models.AdminUser.objects.filter(id=user_id).delete()
            return Response({
                'error_code': 0,
                'message': "Success",
            })
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)


class SearchUser(APIView):
    authentication_classes = [JwtAuthorizationAuthentication, ]

    def get(self, request, *args, **kwargs):
        try:
            params = request.query_params
            search = params["search"]
            user_query = models.AdminUser.objects.filter(Q(name__icontains=search) | Q(email__icontains=search)).all()
            if user_query.exists():
                user_data = adminuser.AdminUserModelSerializer(user_query, many=True).data
                return Response({
                    'error_code': 0,
                    'message': "Success",
                    'data': user_data
                })
            else:
                return resp(1003, {})
        except Exception as e:
            app_log.exception(e)
            return resp(-1, e.args)
